import React from 'react';
import PropTypes from 'prop-types';
import DataSet from '@antv/data-set';
import {Chart, Geom, Axis, Tooltip, Legend, Label, View} from 'bizcharts';
import styles from './style.css';
import {injectIntl} from './intl';
import {Spin, Card, Row, Col} from 'antd';
import moment from 'moment';
const month = moment(new Date()).format('M') === 1 ? 12 : moment(new Date()).format('M') - 1;
const year = moment(new Date()).format('YYYY');
export class TablePanel extends React.PureComponent {
    onClickLegend = (ev, legendItems) => {
        setTimeout(() => {
            const checked = ev.checked;
            const value = ev.item.value;
            if(value === '同比')
                if(checked) {
                    this.chart.get('views')[0].get('geoms')[0].show();
                    this.chart.get('views')[0].get('geoms')[1].show();
                } else {
                    this.chart.get('views')[0].get('geoms')[0].hide();
                    this.chart.get('views')[0].get('geoms')[1].hide();
                }
            const newLegend = legendItems.map(d => {
                if(d.value === value)
                    return Object.assign({}, d, {
                        checked,
                    });
                return d;
            });
            this.chart.filter('type', t => {
                const legendCfg = newLegend.find(i => i.value === t);
                return legendCfg && legendCfg.checked;
            });
            
            this.chart.legend({
                items: newLegend
            });
            this.chart.repaint();
        }, 0);
    }
    render() {
        const {initData} = this.props;
        const dataRateBak = initData.currentSummary.map(v => ({
            country: v.country,
            [`${year}年1-${month}月`]: v.yearMonth,
            [`${year - 1}年1-${month}月`]: v.yearMonthLast,
            同比: v.rate
        }));
        //柱状图与折线图
        const dsRate = new DataSet();
        dsRate.setState('type', '');
        const dvRate = dsRate.createView().source(dataRateBak);
        
        dvRate.transform({
            type: 'fold',
            fields: [`${year}年1-${month}月`, `${year - 1}年1-${month}月`], // 展开字段集
            key: 'type', // key字段
            value: 'value', // value字段
        })
            .transform({
                type: 'filter',
                callback: d => d.type !== dsRate.state.type
            });
        const scale = {
            同比: {
                type: 'linear',
                formatter: val => `${val}%`,
                tickCount: 10,
                // ticks: ['0', '10', '20', '30', '40', '50', '60', '70', '80', '90', '100'],
                // min: 0,
                // max: 1000,
            },
            value: {
                alias: 'BO\n满\n足\n率'
            }
        };
        
        const legendItems = [
            {
                value: `${year}年1-${month}月`,
                marker: {
                    symbol: 'square',
                    fill: '#52c41a',
                    radius: 5
                }
            },
            {
                value: `${year - 1}年1-${month}月`,
                marker: {
                    symbol: 'square',
                    fill: '#41a2fc',
                    radius: 5
                }
            },
            {
                value: '同比',
                marker: {
                    symbol: 'hyphen',
                    stroke: '#fad248',
                    radius: 5,
                    lineWidth: 3
                },
                checked: true
            },
        ];
        return (
            <div>
                <Spin spinning={this.props.loading}>
                    <Card.Meta
                        title={<Row>
                            <Col>
                                {this.props.intl.formatMessage({
                                    id: 'tablePanelMonth.column.currentSummary',
                                    defaultMessage: '截止当月汇总(万/美元)'
                                })}
                            </Col>
                        </Row>}
                        description={<Chart height={550} width={700} forceFit data={dvRate} scale={scale} padding={[30, 50, 100, 50]}
                            onGetG2Instance={c => {
                                this.chart = c;
                            }}>
                            <Legend
                                custom
                                allowAllCanceled
                                items={legendItems}
                                onClick={ev => this.onClickLegend(ev, legendItems)} />
                            <Axis name="country" />
                            <Axis name="value" position={'left'} />
                            <Tooltip />
                            <Geom
                                type="interval"
                                position="country*value"
                                color={['type', value => {
                                    if(value === `${year}年1-${month}月`)
                                        return '#52c41a';
                                    if(value === `${year - 1}年1-${month}月`)
                                        return '#41a2fc';
                                }]}
                                adjust={[{
                                    type: 'dodge',
                                    marginRatio: 1 / 10,
                                }]}>
                                <Label
                                    content="value"
                                    textStyle={{
                                        textAlign: 'center',
                                        fill: '#404040',
                                        fontSize: '12',
                                    }}/>
                            </Geom>
                            <View data={dataRateBak} >
                                <Axis name="同比" position="right" />
                                <Geom type="line" position="country*同比" color="#fad248" size={3} >
                                    <Label
                                        content="同比"
                                        textStyle={{
                                            textAlign: 'middle',
                                            fill: '#404040',
                                            fontSize: '12',
                                        }}/>
                                </Geom>
                                {/* <Geom type="point" position="country*同比" color="#fad248" size={3} >
                                    <Label
                                        content="同比"
                                        textStyle={{
                                            textAlign: 'middle',
                                            fill: '#404040',
                                            fontSize: '12',
                                            textBaseline: 'top'
                                        }}/>
                                </Geom> */}
                            </View>
                        </Chart>}/>
                    <div className={styles.divHeight} />
                </Spin>
            </div>
        );
    }
}

TablePanel.propTypes = {
    initData: PropTypes.object.isRequired,
    hasError: PropTypes.string,
    intl: PropTypes.object,
    loading: PropTypes.bool,
};

import {connect} from 'react-redux';
import {createSelector} from 'reselect';

const getInitData = createSelector(
    state => state.getIn(['page', 'domainData', 'initData']),
    init => {
        const initData = init.toJS();
        const currentSummary = initData ? initData.currentSummary : [];
        const summaryDetails = initData ? initData.summaryDetails : [];
        const monthDetails = initData ? initData.monthDetails : [];
        return {
            currentSummary,
            summaryDetails,
            monthDetails
        };
    }
);
const mapStateToProps = state => ({
    loading: state.getIn(['page', 'domainData', 'initData', 'isFetching']),
    initData: getInitData(state),
});
export default connect(mapStateToProps, null)(injectIntl(TablePanel));
